//http://arshaw.com/fullcalendar/docs/usage/
function getEvents() {
	var eventType = $('#eventFilter').val();

	$('#calendar').empty();
	$('#calendar').fullCalendar(
			{
				header : {
					left : 'prev,next today',
					center : 'title',
					right : 'month,agendaWeek,agendaDay'
				},
				timeFormat : 'HH:mm{ - HH:mm}',
				editable : true,
				events : {
					url : applicationName + '/event/get/?editable=true&type='
							+ eventType
				},
				dayClick : function(date, allDay, jsEvent, view) {
					// alert('dayClick: ' + date + ', ' + allDay + ', ' +
					// jsEvent + ', ' + view.name);
					createEventForm(date);
				},
				eventClick : function(event, jsEvent, view) {
					// alert('eventClick1: ' + event.title + '=' + event.url);
					updateEventForm(event);
					return false;
					/*
					 * if (event.url) { window.open(event.url); return false; }
					 */
				},
				eventDrop : function(event, dayDelta, minuteDelta, allDay,
						revertFunc, jsEvent, ui, view) {
					/*
					 * alert('drop=' + event.id + '.' + event.title + ' at ' +
					 * event.start + '-' + event.end + ' edit=' + event.editable + '
					 * delta=' + dayDelta + '.' + minuteDelta);
					 */
					updateCalendarEvent(event);
				},
				eventResize : function(event, dayDelta, minuteDelta, allDay,
						revertFunc, jsEvent, ui, view) {
					// alert('resize=' + event.id + '.' + event.title + ' at '
					// + event.start + '-' + event.end + ' delta='
					// + dayDelta + '.' + minuteDelta);
					updateCalendarEvent(event);
				},
				eventAfterRender : function(event, element, view) {
					// delete href attribute from "a" elements for dragging in
					// FF
					// @see
					// http://code.google.com/p/fullcalendar/issues/detail?id=1523&can=1&q=eventdrop&colspec=ID%20Type%20Status%20Milestone%20Summary%20Stars
					$('a[class*=fc-event]').attr('href', '#');
				}
			});
}

function createEventForm(date) {
	enableInputs('Creating new event', 'Create');
	$("#btnDelete").hide();
	$("#btnUrl").hide();

	$("#eventId").val(null);
	$("#eventContentId").val(null);
	$('#beginDate').val($.datepicker.formatDate("mm/dd/yy", date));
	$('#spinnerBeginHour').val(date.getHours());
	$('#spinnerBeginMin').val(date.getMinutes());

	$("#eventError").removeClass("alert alert-error").empty();
	$('#createEventModal').modal({
		backdrop : true,
		keyboard : true,
		show : true
	});
}

function updateEventForm(event) {
	// alert('updateEventForm: ' + event.id + '.' + event.title + ' at '+
	// event.start + ' edit=' + event.editable);
	if (!event.editable) {
		$("#createEventModal").find('h3').text('View event');
		$("#eventTitle").attr('disabled', "disabled");
		$("#beginDate").attr('disabled', "disabled");
		$('#endDate').attr('disabled', "disabled");
		$(
				'#spinnerBeginHour, #spinnerBeginMin, #spinnerEndHour, #spinnerEndMin')
				.spinner('disable');
		$("#eventURL").attr('disabled', "disabled");
		$("#isSystem").attr('disabled', "disabled");
		$("#btnCreate").hide();
	} else {
		enableInputs('Update event', 'Update');
	}
	$("#btnDelete").show();
	if (event.url) {
		$("#btnUrl").attr('onclick', "window.open('" + event.url + "')");
		$("#btnUrl").show();
	} else
		$("#btnUrl").hide();

	setEventToForm(event);

	$("#eventError").removeClass("alert alert-error").empty();
	$('#createEventModal').modal({
		backdrop : true,
		keyboard : true,
		show : true
	});
}

function enableInputs(title, btnCreate) {
	$("#eventTitle").removeAttr('disabled');
	$("#beginDate").removeAttr('disabled');
	$('#endDate').removeAttr('disabled');
	$('#spinnerBeginHour, #spinnerBeginMin, #spinnerEndHour, #spinnerEndMin')
			.spinner('enable');
	$("#eventURL").removeAttr('disabled');
	$("#isSystem").removeAttr('disabled');
	$("#createEventModal").find('h3').text(title);
	$("#btnCreate").text(btnCreate);
	$("#btnCreate").show();
}

function deleteCalendarEvent() {
	blockUI();
	eventId = $("#eventId").val();
	// alert('deleteCalendarEvent');
	var event = getEventFromForm();
	$.ajax({
		async : false,
		type : "get",
		dataType : "json",
		url : applicationName + '/event/delete/' + eventId,
	}).done(function(result) {
		if (result.error == null) {
			$('#createEventModal').modal('hide');
			// http://arshaw.com/fullcalendar/docs/event_data/
			$('#calendar').fullCalendar('removeEvents', eventId);
		} else {
			$("#eventError").addClass("alert alert-error").html(result.error);
		}
	});
	unblockUI();
}

function createUpdateCalendarEvent() {
	blockUI();
	var event = getEventFromForm();
	// alert('createUpdateCalendarEvent: ' + event.id + '.' + event.title + ' at
	// ' + event.start);
	$.ajax({
		async : false,
		type : "post",
		dataType : "json",
		url : applicationName + '/event/createUpdate',
		contentType : 'application/json',
		data : JSON.stringify(event)
	}).done(function(result) {
		if (result.error == null) {
			$('#createEventModal').modal('hide');
			if (event.id) {
				// event must be the original Event Object for an event, not
				// merely a reconstructed object.
				// $('#calendar').fullCalendar('updateEvent', event);
				$('#calendar').fullCalendar('removeEvents', event.id);
				$('#calendar').fullCalendar('renderEvent', event, true);
			} else {
				$('#calendar').fullCalendar('renderEvent', {
					id : result.eventId,
					title : event.title,
					allDay : event.allDay,
					start : event.start,
					end : event.end,
					url : event.url,
					color : event.color,
					editable : event.editable
				}, true);
			}
		} else {
			$("#eventError").addClass("alert alert-error").html(result.error);
		}
	});
	unblockUI();
}

// non visual update: drag&drop, resize
function updateCalendarEvent(eventA) {
	blockUI();

	event = new Object();
	event.id = eventA.id;
	event.contentId = eventA.contentId;
	// user
	event.title = eventA.title;
	event.start = getDateAsString(eventA.start);
	event.end = getDateAsString(eventA.end);
	event.allDay = eventA.allDay;
	event.url = eventA.url;
	event.system = eventA.system;
	event.color = eventA.color;
	event.editable = eventA.editable;

	// alert('createUpdateCalendarEvent: ' + event.id + '.' + event.title + ' at
	// ' + event.start);
	$.ajax({
		async : false,
		type : "post",
		dataType : "json",
		url : applicationName + '/event/createUpdate',
		contentType : 'application/json',
		data : JSON.stringify(event)
	}).done(function(result) {
		if (result.error != null) {
			alert("Error while updating event: " + result.error);
			getEvents();
		}
	});
	unblockUI();
}

function getEventFromForm() {
	event = new Object();
	event.id = $("#eventId").val();
	event.contentId = $("#eventContentId").val();
	event.title = $("#eventTitle").val();
	if ($('#beginDate').val() == "")
		event.start = "";
	else
		event.start = $('#beginDate').val() + " "
				+ $('#spinnerBeginHour').val() + ":"
				+ $('#spinnerBeginMin').val();
	if ($('#endDate').val() == "")
		event.end = "";
	else
		event.end = $('#endDate').val() + " " + $('#spinnerEndHour').val()
				+ ":" + $('#spinnerEndMin').val();
	event.url = $('#eventURL').val()
	event.system = $("#isSystem").is(':checked');
	if (event.contentId.indexOf("exam_") != -1)
		event.color = 'green';
	else {
		event.color = 'blue';
		if (event.system)
			event.color = 'red';
	}
	event.editable = true;
	// alert(event.title + '=' + event.start + '=' + event.end + '=' + event.url
	// + '=' + event.system + '=' + event.color);
	return event;
}

function setEventToForm(event) {
	$("#eventId").val(event.id);
	$("#eventContentId").val(event.contentId);
	$("#eventTitle").val(event.title);
	$('#beginDate').val($.datepicker.formatDate("mm/dd/yy", event.start));
	$('#spinnerBeginHour').val(event.start.getHours());
	$('#spinnerBeginMin').val(event.start.getMinutes());
	if (event.end) {
		$('#endDate').val($.datepicker.formatDate("mm/dd/yy", event.end));
		$('#spinnerEndHour').val(event.end.getHours());
		$('#spinnerEndMin').val(event.end.getMinutes());
	}
	$('#eventURL').val(event.url)
	$("#isSystem").attr('checked', event.system);
}

// return date as "mm/dd/yyyy HH:mi",
function getDateAsString(date) {
	if (date)
		return $.fullCalendar.formatDate(date, 'MM/dd/yyyy HH:mm');
	else
		return '';
}
